package com.test.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2020-06-17 下午12:40
 */
public class CglibProxy implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("this method is using cglib proxy");
        return methodProxy.invokeSuper(o, objects);
    }


    /**
     * 获取代理类
     *
     * @param clazz
     * @return
     */
    public Object getProxy(Class<?> clazz) {
        Enhancer enhancer = new Enhancer();
        // 目标对象类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        // 通过字节码技术创建目标对象类的子类实例作为代理
        return enhancer.create();
    }
}
